package com.dkd.findmyfriends;

import java.util.List;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class HighScoresActivity extends Activity implements OnClickListener, OnItemSelectedListener {

	private boolean localSelected = true;
	private Spinner spinner;
	private TextView firstColHeader;
	private GifView loadingGif;
	
    @TargetApi(11)
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
            getActionBar().setDisplayHomeAsUpEnabled(true);
		} else {
			requestWindowFeature(Window.FEATURE_NO_TITLE);
		}
        setContentView(R.layout.activity_high_scores);

        firstColHeader = (TextView)findViewById(R.id.firstColumnHeader);
        
        //setup loading gif
        loadingGif = (GifView) findViewById(R.id.loading);
//        loadingGif.setGifId(R.drawable.loading);
        loadingGif.setVisibility(View.INVISIBLE);
        
        //grid size
        spinner = (Spinner) findViewById(R.id.gridSizeHSSpinner);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.grid_sizes, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(this);
        spinner.setSelection(GameSettings.getSettingsPosSelected());
        //setting spinner selection will kick off the build HSTable
    }
    
    private void buildHSTable() {
    	TableLayout highScoreTable = (TableLayout) findViewById(R.id.highScoreTable);
    	//remove all but the header
    	for(int childIndex = highScoreTable.getChildCount()-1; childIndex > 0 ; childIndex--) {
    		highScoreTable.removeViewAt(childIndex);
    	}
    	
    	firstColHeader.setText(localSelected ? "Grid Size" : "");
   		findViewById(R.id.resetBtn).setVisibility(localSelected ? View.VISIBLE : View.INVISIBLE);
   		findViewById(R.id.gridSizeHSSpinner).setVisibility(localSelected ? View.INVISIBLE : View.VISIBLE);
   		
   		if(localSelected) {
   			buildLocalHSTable(highScoreTable);
   		} else {
   			buildGlobalHSTable(highScoreTable);
   		}
    }

	private void buildLocalHSTable(TableLayout highScoreTable) {
        loadingGif.setVisibility(View.INVISIBLE);
    	String[] gridSizes = getResources().getStringArray(R.array.grid_sizes);
        for(int i = 0; i < gridSizes.length; i++) {
			TableRow tr = new TableRow(this);
			tr.setLayoutParams(new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
			//grid size
			String gridSize = gridSizes[i];
			addTextViewToRow(tr, gridSize);

			SharedPreferences settings = getSharedPreferences(SPKeys.PREFS_FILE_NAME, MODE_PRIVATE);
			//fewest clicks user
			String fcUser = settings.getString(SPKeys.FEWEST_CLICKS + gridSize + SPKeys.NAME, "N/A");
			addTextViewToRow(tr, fcUser);
			//fewest clicks
			int fcI = settings.getInt(SPKeys.FEWEST_CLICKS + gridSize, -1);
			String fc = (fcI == -1) ? "N/A" : String.valueOf(fcI);
			addTextViewToRow(tr, fc);
			
			//fastest time user
			String ftUser = settings.getString(SPKeys.FASTEST_TIME + gridSize + SPKeys.NAME, "N/A");
			addTextViewToRow(tr, ftUser);
			//fastest time
			long ftL = settings.getLong(SPKeys.FASTEST_TIME + gridSize, -1);
			String ft = (ftL == -1) ? "N/A" : GameSettings.getTimeString(ftL);
			addTextViewToRow(tr, ft);
			
			//add row to TableLayout
			highScoreTable.addView(tr, new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        }
	}
    
    private void buildGlobalHSTable(TableLayout highScoreTable) {
        loadingGif.setVisibility(View.VISIBLE);
    	BuildGHSTableRunnable run = new BuildGHSTableRunnable(highScoreTable);
    	Database.getTop100Scores(spinner.getSelectedItem().toString(), run);
	}
    
    public class BuildGHSTableRunnable implements Runnable {
    	
    	public List<GlobalTableRow> rows;
		public TableLayout highScoreTable;
		
		public BuildGHSTableRunnable(TableLayout highScoreTable) {
			this.highScoreTable = highScoreTable;
		}
    	
		public void run() {
	        loadingGif.setVisibility(View.INVISIBLE);
	        if(rows != null && rows.size() > 0) {
	    		for(int i = 0; i < 20 && i < rows.size(); i++) {
	        		GlobalTableRow r = rows.get(i);
	        		TableRow tr = new TableRow(HighScoresActivity.this);
	    			tr.setLayoutParams(new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
	    			addTextViewToRow(tr, String.valueOf(i+1));
	    			addTextViewToRow(tr, r.userClicks);
	    			addTextViewToRow(tr, r.clicks);
	    			addTextViewToRow(tr, r.userTime);
	    			addTextViewToRow(tr, r.time);
	    			
	    			//add row to TableLayout
	    			highScoreTable.addView(tr, new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
	        	}
	        } else {
	        	TableRow tr = new TableRow(HighScoresActivity.this);
    			tr.setLayoutParams(new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    			addTextViewToRow(tr, "No Results", 5);
    			//add row to TableLayout
    			highScoreTable.addView(tr, new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
	        }
		}
    }
    
    private void addTextViewToRow(TableRow tr, String text) {
//    	TextView tv = new TextView(this);
//		tv.setText(text);
//		tv.setLayoutParams(new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
//		tv.setGravity(Gravity.CENTER);
//		tv.setTextColor(getResources().getColor(R.color.white));
//		tr.addView(tv);
    	addTextViewToRow(tr, text, 1);
    }
    
    private void addTextViewToRow(TableRow tr, String text, int colSpan) {
    	TextView tv = new TextView(this);
		tv.setText(text);
		TableRow.LayoutParams params = new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		params.span = colSpan;
//		tv.setLayoutParams(params);
		tv.setGravity(Gravity.CENTER);
		tv.setTextColor(getResources().getColor(R.color.white));
		tr.addView(tv, params);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_high_scores, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                NavUtils.navigateUpFromSameTask(this);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.okBtn:
			finish();
			break;
		case R.id.resetBtn:
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("Are you sure you want to reset all the highscores?");
			builder.setPositiveButton("Reset", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   	SharedPreferences settings = getSharedPreferences(SPKeys.PREFS_FILE_NAME, MODE_PRIVATE);
			   			SharedPreferences.Editor editor = settings.edit();
			   			String[] gridSizes = getResources().getStringArray(R.array.grid_sizes);
			   	        for(int i = 0; i < gridSizes.length; i++) {
			   				String gridSize = gridSizes[i];
			   				editor.remove(SPKeys.FASTEST_TIME + gridSize);
			   				editor.remove(SPKeys.FASTEST_TIME + gridSize + SPKeys.NAME);
			   				editor.remove(SPKeys.FEWEST_CLICKS + gridSize);
			   				editor.remove(SPKeys.FEWEST_CLICKS + gridSize + SPKeys.NAME);
			   	        }
			   	        editor.commit();
			   	        //reset table
			   	        buildHSTable();			
		           }
		     	});
			builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		               // User cancelled the dialog
		           }
		       });
			AlertDialog dialog = builder.create();
			dialog.show();
			break;
		case R.id.localRadio:
			localSelected = true;
			buildHSTable();
			break;
		case R.id.globalRadio:
			localSelected = false;
			buildHSTable();
			break;
		default:
			break;
		}
	}

	public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
		buildHSTable();
	}

	public void onNothingSelected(AdapterView<?> parent) {
	}
	
	public static class GlobalTableRow {
		public String userClicks;
		public String userTime;
		public String clicks;
		public String time;		
	}
	
}
